/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eleric.rememome.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
//import android.widget.Button;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.LayoutParams;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.eleric.rememome.R;
import com.eleric.rememome.db.MemoDbAdaptor;
import com.eleric.rememome.db.factory.MemoDbAdaptorFactory;
import com.eleric.rememome.db.factory.impl.MemoDbAdaptorFactoryVer2;
import com.eleric.rememome.memo.MemoCategory;
import com.eleric.rememome.priority.PriorityColor;
import com.eleric.rememome.priority.PriorityColorFactory;
import com.eleric.rememome.priority.impl.PriorityColorPriorityTypeImpl;
import com.eleric.rememome.type.MemoStatusType;
import com.eleric.rememome.type.PriorityType;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 *
 * @author MWaldman
 */
public class AddActivity extends Activity
{

    protected MemoDbAdaptorFactory dbAdapterFactory;
    protected EditText editText;
    protected RadioGroup rGroup;
    protected SeekBar seekBar;
    protected TextView priorityView;
    protected Button okButton;
    protected Button speakButton;
    protected Button nextWordButton;
    public static final String MEMO_REF = "memoRef";
    protected SpeechRecognizer sr;
    protected static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
    protected ArrayList<String> matches;
    protected int matchesIndex;
    protected PriorityColor priorityColor;
////    private Handler mHandler;

    public AddActivity()
    {
        super();
        dbAdapterFactory = new MemoDbAdaptorFactoryVer2();
        priorityColor = PriorityColorFactory.createPriorityColor();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        refreshPriorityView();
        nextWordStatus();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        hideKeyboard();
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
////        mHandler = new Handler();
        // ToDo add your GUI initialization code here
        MemoDbAdaptor dbAdapter;
        OnKeyListener onKeyListener;
        SeekBar.OnSeekBarChangeListener onSeekBarChangeListener;
//        final EditText editText;
//        final RadioGroup rGroup;
//        final SeekBar seekBar;
        RadioButton rButton;
        LayoutParams lParams;
        List<MemoCategory> categories;
//        final Button ok;
//        final Button cancel;
        setContentView(R.layout.add_text); 
        editText = (EditText) findViewById(R.id.add_item);
        rGroup = (RadioGroup) findViewById(R.id.radio_categories);
        seekBar = (SeekBar) findViewById(R.id.priority_seekbar);
        seekBar.setMax(PriorityType.getMaxPriority());
        okButton = (Button) findViewById(R.id.ok_add_item);
        okButton.setText("ADD");
        speakButton = (Button) findViewById(R.id.voice_add_item);
        nextWordButton = (Button) findViewById(R.id.next_word_add_item);

//        seekBar.setMax(1000);
//        seekBar.setProgress(500);
        priorityView = (TextView) findViewById(R.id.priority_show_value);
        seekBar.setProgress(getResources().getInteger(R.integer.priority_default));

        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities =
                pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
//        for (ResolveInfo ri : activities)
//        {
//            editText.setText(editText.getText() + " : " + ri.toString());
//        }

        if (activities.size() != 0)
        {
            speakButton.setEnabled(true);
        }
        else
        {
            speakButton.setEnabled(false);
        }
        matches = new ArrayList<String>();
        matchesIndex = 0;
////        refreshVoiceSettings();

//        sr = SpeechRecognizer.createSpeechRecognizer(this);
//        sr.setRecognitionListener(new RecognitionListener()
//        {
//
//            public void onReadyForSpeech(Bundle arg0)
//            {
//            }
//
//            public void onBeginningOfSpeech()
//            {
//            }
//
//            public void onRmsChanged(float arg0)
//            {
//            }
//
//            public void onBufferReceived(byte[] arg0)
//            {
//            }
//
//            public void onEndOfSpeech()
//            {
//            }
//
//            public void onError(int error)
//            {
//                Log.d(AddActivity.class.toString(), "Error: " + error);
//            }
//
//            public void onResults(Bundle results)
//            {
//                String str = new String();
//                ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//                for (int i = 0; i < data.size(); i++)
//                {
//                    str += data.get(i);
//                }
//                editText.setText(String.valueOf(data.size()));
//            }
//
//            public void onPartialResults(Bundle arg0)
//            {
//            }
//
//            public void onEvent(int arg0, Bundle arg1)
//            {
//            }
//        });


        //        refreshPriorityView();
        //        ok = (Button) findViewById(R.id.ok_add_item);
        //        cancel = (Button) findViewById(R.id.ok_add_item);

        onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener()
        {

            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
            {
                refreshPriorityView();
            }

            public void onStartTrackingTouch(SeekBar arg0)
            {
            }

            public void onStopTrackingTouch(SeekBar arg0)
            {
            }
        };

        onKeyListener = new OnKeyListener()
        {

            public boolean onKey(View arg0, int keyCode, KeyEvent event)
            {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER))
                {
                    addItem(editText);
                    return true;
                }
                return false;
            }
        };
//        ok.setOnClickListener(new View.OnClickListener()
//        {
//
//            public void onClick(View arg0)
//            {
//                addItem(editText);
//            }
//        });
        seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
        try
        {
            editText.setOnKeyListener(onKeyListener);
        } catch (Exception e)
        {
            System.out.println(e.toString());
            e.printStackTrace(System.out);
        }
        dbAdapter = dbAdapterFactory.createDbAdapter(this);
        dbAdapter.open();

        lParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        categories = dbAdapter.listCategories();
        for (MemoCategory mc : categories)
        {
            rButton = new RadioButton(this);
            rButton.setLayoutParams(lParams);
            rButton.setText(mc.getShortName());
            rButton.setTag(mc);
            rGroup.addView(rButton);
            if (mc.getShortName().equalsIgnoreCase("TO GET"))
            {
                rGroup.check(rButton.getId());
//                currentSelectedCategory = mc;
            }
        }
//        rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//
//            public void onCheckedChanged(RadioGroup group, int checkId)
//            {
//                View rButton = group.findViewById(checkId);
//                currentSelectedCategory = (MemoCategory) rButton.getTag();
//            }
//        });
    }

    protected void refreshPriorityView()
    {
        int priority = seekBar.getProgress();
        PriorityType ptype;
        ptype = PriorityType.getType(priority);
        priorityView.setText(ptype.name());
        priorityView.setTextColor(ptype.getColor());
    }

    protected void hideKeyboard()
    {
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    public void addItem(View view)
    {
//        final RadioGroup rGroup;
//        final EditText editText;
//        editText = (EditText) findViewById(R.id.add_item);
//        rGroup = (RadioGroup) findViewById(R.id.radio_categories);
        addItem(editText, rGroup);
        hideKeyboard();
    }

    private void addItem(EditText editText, RadioGroup rGroup)
    {
        MemoDbAdaptor dbAdapter;
        RadioButton rb;
        int rbIndex;
        String memoName;
        MemoCategory cat;
        rbIndex = rGroup.getCheckedRadioButtonId();
        rb = (RadioButton) rGroup.findViewById(rbIndex);
//        priority =  R.integer.priority_default;
        memoName = editText.getText().toString();
        if (!memoName.trim().equals(""))
        {
//        cat = currentSelectedCategory;
            cat = (MemoCategory) rb.getTag();
            Calendar now = Calendar.getInstance();
            dbAdapter = dbAdapterFactory.createDbAdapter(this);
            dbAdapter.open();
            // Insert with default priority for now
            dbAdapter.insertMemo(memoName, cat.getId(), MemoStatusType.OPEN.getStatusId(),
                    now.getTime(), now.getTime(), seekBar.getProgress());
            Toast.makeText(AddActivity.this, "Saved: " + editText.getText(),
                    Toast.LENGTH_SHORT).show();
            clearItem(editText);
//            editText.setText("");
//            seekBar.setProgress(getResources().getInteger(R.integer.priority_default));
//            refreshPriorityView();
            dbAdapter.close();
        }
    }

    public void clearItem(View view)
    {
//        final EditText editText;
//        editText = (EditText) findViewById(R.id.add_item);
        editText.setText("");
        seekBar.setProgress(getResources().getInteger(R.integer.priority_default));
        refreshPriorityView();
        hideKeyboard();
        matches = new ArrayList<String>();
        matchesIndex = 0;
        nextWordStatus();
    }

    protected void nextWordStatus()
    {
        if (matches.size() != 0)
        {
            nextWordButton.setEnabled(true);
        }
        else
        {
            nextWordButton.setEnabled(false);
        }
    }

    public MemoDbAdaptorFactory getDbAdapterFactory()
    {
        return dbAdapterFactory;
    }

    public void setDbAdapterFactory(MemoDbAdaptorFactory dbAdapterFactory)
    {
        this.dbAdapterFactory = dbAdapterFactory;
    }

    public void getSpeech(View v)
    {
//        if (v.getId() == R.id.voice_add_item)
//        {
//            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
//                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//            intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "voice.recognition.test");
//            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
//            sr.startListening(intent);
//        }
        startVoiceRecognitionActivity();
    }

    /**     * Fire an intent to start the speech recognition activity.     */
    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        // Specify the calling package to identify your application
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
        // Display an hint to the user about what he should say.
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Name an Item");
        // Given an hint to the recognizer about what the user is going to say
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        // Specify how many results you want to receive. The results will be sorted
        // where the first result is the one with higher confidence.
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
        // Specify the recognition language. This parameter has to be specified only if the
        // recognition has to be done in a specific language and not the default one (i.e., the
        // system locale). Most of the applications do not have to set this parameter.
//        if (!mSupportedLanguageView.getSelectedItem().toString().equals("Default"))
//        {
//            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
//                    mSupportedLanguageView.getSelectedItem().toString());
//        }
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK)
        {
            // Fill the list view with the strings the recognizer thought it could have heard
            matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            matchesIndex = 0;
//            ArrayList<String> matches = data.getStringArrayListExtra(
//                    RecognizerIntent.EXTRA_RESULTS);
            if (matches.size() > 0)
            {
                editText.setText(matches.get(0));
            }
//            mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
//                    matches));
        }
        else if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode != RESULT_OK)
        {
            editText.setText("Speech Result Code: " + resultCode);
        }
        nextWordStatus();
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void nextWord(View v)
    {
        int s = matches.size();
        if (s != 0)
        {
            matchesIndex++;
            if (matchesIndex >= s)
            {
                matchesIndex = 0;
            }
            editText.setText(matches.get(matchesIndex));
        }
        else
        {
            matchesIndex = 0;
        }
    }
////    private void refreshVoiceSettings()
////    {
////        sendOrderedBroadcast(RecognizerIntent.getVoiceDetailsIntent(this), null,
////                new SupportedLanguageBroadcastReceiver(), null, Activity.RESULT_OK, null, null);
////    }
    /**
     * Handles the response of the broadcast request about the recognizer supported languages.
     *
     * The receiver is required only if the application wants to do recognition in a specific
     * language.
     */
////    private class SupportedLanguageBroadcastReceiver extends BroadcastReceiver
////    {
////
////        @Override
////        public void onReceive(Context context, final Intent intent)
////        {
////            Log.i(this.getClass().toString(), "Receiving broadcast " + intent);
////
////            final Bundle extra = getResultExtras(false);
////
////            if (getResultCode() != Activity.RESULT_OK)
////            {
////                mHandler.post(new Runnable()
////                {
////
////                    @Override
////                    public void run()
////                    {
////                        showToast("Error code:" + getResultCode());
////                    }
////                });
////            }
////
////            if (extra == null)
////            {
////                mHandler.post(new Runnable()
////                {
////
////                    @Override
////                    public void run()
////                    {
////                        showToast("No extra");
////                    }
////                });
////            }
////
//////            if (extra.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES))
//////            {
//////                mHandler.post(new Runnable()
//////                {
//////
//////                    @Override
//////                    public void run()
//////                    {
//////                        updateSupportedLanguages(extra.getStringArrayList(
//////                                RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES));
//////                    }
//////                });
//////            }
//////
//////            if (extra.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE))
//////            {
//////                mHandler.post(new Runnable()
//////                {
//////
//////                    @Override
//////                    public void run()
//////                    {
//////                        updateLanguagePreference(
//////                                extra.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE));
//////                    }
//////                });
//////            }
////        }
////
////        private void showToast(String text)
////        {
////            Toast.makeText(AddActivity.this, text, 1000).show();
////        }
////    }
}
